var http = require('http');
var path = require('path');

//var async = require('async');
var socketio = require('socket.io');
var express = require('express');

var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);

router.use(express.static(path.resolve(__dirname, 'html_tests')));


var games = {};
console.log("conectado");


io.on('connection', function(socket){
    console.log('Novo usuário conectado!');

    socket.emit("welcome", {message : "Seja bem vindo"}, function (dados) {
        console.log("callback recebido", dados);
    });

    socket.on("disconnect", function(){
        if(!socket.game_name) return;
        delete games[socket.nickname];
        //sockets.splice(sockets.indexOf(socket), 1);
    });
    socket.on("message_to", function(message){
        var newMessage = {

            text : message.text
        };
        games[message.to].emit("new_message", newMessage);
    });

    socket.on("create_game", function(user, callback){ 
        socket.game_name = user.name;
        games[socket.game_name] = socket;
        callback("");

        console.log("Novo Jogo Criado", user);
    });
});

server.listen(process.env.PORT || 3001, process.env.IP || "0.0.0.0", function(){
    var addr = server.address();
    console.log("Server iniciado na porta: ", addr.address + ":" + addr.port);
});